5. Control Structures & Data Handling
Higher Secondary · Computer Applications / Commerce

Python Control Structures
and Data Handling

Control structures decide what happens next in a program — decision-making with if-elif-else and match-case, and repetition with for and while loops. This chapter also covers Python's core data structures: Lists, Tuples, Sets, and Dictionaries.

"Programs must be written for people to read, and only incidentally for machines to execute." — Harold Abelson
5.2.1 · Live Tool

Grade Checker (if-elif-else)

This mirrors Example 5.1 from the chapter — an if-elif-else chain that checks marks against several conditions in order, and executes only the first block that matches.

Enter Marks → Grade

● live
marks =
Grade
—
Matched condition
—
Branch reached
—
91 82 73 65 55 42 33 12
Only the first true condition in the chain runs — even if a later elif would also be true, it is never checked.
Example 5.1 — Python source
marks = int(input("Enter marks: ")) if marks >= 90: print("Grade A+") elif marks >= 80: print("Grade A") elif marks >= 70: print("Grade B+") elif marks >= 60: print("Grade B") elif marks >= 50: print("Grade C+") elif marks >= 40: print("Grade C") elif marks >= 30: print("Grade D+") else: print("Grade D")
5.2.1

Conditional Statements

Conditional statements let a program make decisions and are the backbone of logical flow control. Python's two main conditional constructs are if-elif-else and match-case.

Why control structures matter

Decision making · Flow control · Iterations · Improved efficiency & flexibility · Real-world applications.

Code Blocks & Indentation

In Python, indentation (whitespace at the start of a line) is the only way to define a code block — it is mandatory and directly affects execution.

a. if-elif-else Statement

Rules

The if checks the first condition. If false, each elif checks another. If none are true, else runs. Multiple elif branches are allowed; only one else, and it must come last. Neither elif nor else is compulsory.

Syntax

if condition: code block elif condition: code block else: code block

b. match-case Statement Python 3.10+

Introduced in Python 3.10 as part of structural pattern matching, match-case is an alternative to the switch statement found in C++, Java, or JavaScript. It compares a value (the pattern) against multiple cases and runs the code for the first match. The underscore _ acts as the default case.

Syntax
match variable: case pattern1: # code block case pattern2: # code block case _: # default block
Example 5.2
day = "Monday" match day: case "Monday": print("Start of the week") case "Friday": print("Weekend is near") case _: print("Regular day")

Cleaner

More readable than long if-elif-else chains.

Advanced patterns

Supports matching tuples, lists, and conditions within patterns.

Maintainable

Enhances code maintainability for complex conditional logic.

5.2.2

Looping Statements

Looping executes a set of instructions repeatedly until a condition is met — reducing the need to write the same code multiple times. A loop checks a condition before or after running its block; when the condition becomes false, it stops automatically.

(i) for loop

A for loop iterates over a sequence (list, string, etc.) — "do something for each item in this group." The code block runs once per item, until the sequence is exhausted.

Syntax & Example 5.3 — Looping through a string
for loop_variable in sequence: # do required operation with loop_variable word = "hello" for letter in word: print(letter) # Output: h e l l o (one per line)
Example 5.4 — range(start, stop, step)
for i in range(1, 6): print(i) # Output: 1 2 3 4 5 (stop is NOT inclusive; default start=0, step=1)
Example 5.5 — Nested for loop (multiplication table)
for i in range(1, 4): for j in range(1, 4): print(i, "*", j, "=", i * j) # 1*1=1 1*2=2 1*3=3 2*1=2 2*2=4 2*3=6 3*1=3 3*2=6 3*3=9

break statement

Immediately stops the loop when a condition is met — prevents unnecessary iterations.

continue statement

Skips the current iteration and moves to the next one, without stopping the whole loop.

for loop with else

If the for loop finishes normally the statement in the else clause will be executed

Example 5.6 (break) & Example 5.8 (vowel counter)
for num in range(1, 10): if num == 5: break print(num) # Output: 1 2 3 4 sentence = "Python is fun" vowels = "aeiou" count = 0 for char in sentence: if char.lower() in vowels: count += 1 print("Number of vowels:", count) # Output: 3
Example 5.9 — for loop with else (runs when the loop finishes normally)
for i in range(3): print("Loop:", i) else: print("Loop finished") # Loop: 0 Loop: 1 Loop: 2 Loop finished

(ii) while loop

A while loop repeats a block based on a condition evaluated before each iteration. Once the condition becomes False, the loop terminates.

Syntax & Example 5.10
while condition: block of code count = 1 while count <= 5: print("Count is:", count) count += 1 # Count is: 1 2 3 4 5

Infinite loops

Occur when the condition never becomes False — usually because the loop control variable is never updated (e.g. forgetting i += 1).

while loop with break statement

The break statement is used to exit from the loop, even if the condition is still true.

while loop with continue statement

The continue statement allows the while loop to skip the current iteration and moves to the next one.

Nested while loop

A while loop can be placed inside another — Example 5.15 prints all combinations of i (1–3) and j (1–2).

Example 5.12 (break) & Example 5.14 (while...else)
i = 1 while i <= 10: print(i) if i == 5: break i += 1 # Output: 1 2 3 4 5 i = 0 while i < 4: print("i =", i) i += 1 else: print("Loop finished") # i = 0 i = 1 i = 2 i = 3 Loop finished

Input validation

Repeatedly ask for input until valid data is entered.

Menu-driven programs

Keep displaying options until the user chooses to exit.

Game loops

Continuously run game logic until the player quits.

5.3

Lists

A list stores multiple items in a single variable — one of Python's four built-in collection types (the others being Tuple, Set, and Dictionary). Lists are created with square brackets [ ] and are the most flexible of the four.

Characteristics of Lists

Ordered

Items keep a defined order unless explicitly changed.

Mutable

Can add, remove, or modify elements after creation.

Allow duplicates

The same value can appear more than once.

Indexed

Each item has a unique index, starting from 0.

Example 5.16–5.19 — create, access, slice, modify
fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple print(fruits[-1]) # cherry (negative index from the end)

Slicing lists

Slicing is used to access a range of elements from a list.

list[start:stop:step] numbers = [10, 20, 30, 40, 50] print(numbers[1:4]) # [20, 30, 40]

Mofifying lists

Lists are mutable so that their elements can be changed.

fruits[1] = "blueberry" print(fruits) # ['apple', 'blueberry', 'cherry']
Adding & removing elements
fruits.append("orange") # adds to the end fruits.insert(1, "grape") # adds at a specific index fruits.extend(["kiwi", "melon"]) # adds elements from another list fruits.remove("banana") # removes first occurrence of a value fruits.pop(2) # removes item at a given index fruits.clear() # removes all items

List Methods Summary

MethodDescription
append()Adds an item to the end
insert()Inserts item at specified index
extend()Adds multiple items
remove()Removes first occurrence of item
pop()Removes item at index
clear()Removes all items
index()Returns index of first occurrence
count()Returns number of occurrences
sort()Sorts the list in ascending order
reverse()Reverses the list
copy()Returns a shallow copy of the list
Example 5.20 (average), 5.22 (remove duplicates), 5.23 (list comprehension), 5.24 (nested list)
marks = [85, 90, 78, 92] average = sum(marks) / len(marks) print("Average marks:", average) # 86.25 items = ["apple", "banana", "apple", "orange"] unique_items = [] for item in items: if item not in unique_items: unique_items.append(item) print(unique_items) # ['apple', 'banana', 'orange'] squares = [x*x for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] matrix = [[1, 2], [3, 4], [5, 6]] print(matrix[1][0]) # 3
5.4

Tuples

A tuple is like a list, but immutable — its contents cannot change once created. This makes tuples ideal for fixed collections such as coordinates, configuration settings, or constants. Tuples use parentheses ( ).

Creating tuples
fruits = ("apple", "banana", "cherry") numbers = (10, 20, 30) colors = "red", "green", "blue" # parentheses optional empty = () single = ("apple",) # trailing comma required for one item
Example 5.25–5.28 — access, slice, operations, methods
fruits = ("apple", "banana", "cherry") print(fruits[0]) # apple print(fruits[-1]) # cherry numbers = (10, 20, 30, 40, 50) print(numbers[1:4]) # (20, 30, 40) print(numbers[::2]) # (10, 30, 50) -- step value a = (1, 2); b = (3, 4) print(a + b) # (1, 2, 3, 4) -- concatenation print(("Hi",) * 3) # ('Hi', 'Hi', 'Hi') -- repetition numbers = (1, 2, 3, 2, 2) print(numbers.count(2)) # 3 print(numbers.index(3)) # 2

Limited methods

Because tuples are immutable, they only support count() and index().

Membership & length

Use in to test membership and len() to get the number of items — the same as lists.

5.5

Sets

A set stores multiple items, but is unordered, unindexed, and disallows duplicates — ideal for filtering duplicates and performing mathematical operations like union and intersection. Sets use curly braces { } or set().

Unordered & Unindexed

No guaranteed order; elements cannot be accessed by index.

No duplicates

Duplicate values are automatically removed.

Immutable elements, mutable container

Elements must be immutable (numbers, strings, tuples) — but the set itself can grow or shrink.

Creating & modifying sets
fruits = {"apple", "banana", "cherry"} colors = set(["red", "green", "blue"]) empty = set() # NOT {} -- that creates a dictionary items = {"apple", "banana", "apple"} print(items) # {'apple', 'banana'} -- duplicates removed fruits.add("orange") # adds a single element fruits.update(["kiwi", "melon"]) # adds multiple elements fruits.discard("banana") # removes without error if not found fruits.pop() # removes a random item
Example 5.30–5.32 — Set operations
a = {1, 2, 3} b = {3, 4, 5} print(a | b) # Union → {1, 2, 3, 4, 5} print(a & b) # Intersection → {3} print(a - b) # Difference → {1, 2} print(a ^ b) # Symmetric Difference → {1, 2, 4, 5} x = {1, 2} y = {1, 2, 3, 4} print(x.issubset(y)) # True

Set Methods Summary

MethodDescription
add()Adds a single element
update()Adds multiple elements
remove()Removes specified element (error if not found)
discard()Removes specified element (no error)
pop()Removes a random element
clear()Removes all elements
union()Returns union of sets
intersection()Returns common elements
difference()Returns elements in one set but not the other
symmetric_difference()Returns elements in either set but not both
issubset()Checks if one set is a subset of another
issuperset()Checks if one set is a superset of another
isdisjoint()Checks if sets have no common elements
5.6

Dictionaries

A dictionary stores data as key–value pairs — also called associative arrays or hash maps in other languages. Instead of numeric indices, dictionaries use unique keys to access values, making them ideal for structured data.

Key–Value pairs

Each item pairs a key with its associated value.

Ordered (3.7+)

From Python 3.7 onward, dictionaries preserve insertion order.

Unique keys

A repeated key overwrites the previous value.

Immutable keys

Keys must be strings, numbers, or tuples — lists/dicts cannot be keys.

Example 5.33–5.36 — create, access, modify
student = {"name": "Aryananda", "age": 17, "class": "12A"} # or: student = dict(name="Sreerag", age=17, class_="CSE") mark = {'Diya': 70, 'Biju': 65, 'Thomas': 58} print(mark['Biju']) # 65 (KeyError if key missing) print(mark.get('Biju')) # 65 (safer — returns None if missing) mark['Fathima'] = 75 # adding a new key-value pair mark['Biju'] = 68 # updating an existing key del mark['Diya'] # removing a key-value pair print(mark) # {'Biju': 68, 'Thomas': 58, 'Fathima': 75}
Removing elements
student.pop("class_") # removes the item with the specified key student.popitem() # removes the last inserted item (3.7+) del student["age"] # deletes a key-value pair student.clear() # removes all items

Dictionary Methods Summary

MethodDescription
get(key)Returns the value for the key
keys()Returns a view of all keys
values()Returns a view of all values
items()Returns a view of all key-value pairs
update(dict2)Updates the dictionary with another dictionary
pop(key)Removes the item with the specified key
popitem()Removes the last inserted item
clear()Removes all items
copy()Returns a shallow copy of the dictionary
setdefault()Returns value of a key; sets default if not found
Recap

List, Tuple, Set & Dictionary — Comparison

All four are built-in Python collection types, but each fits a different purpose.

FeatureListTupleSetDictionary
Syntax[ ]( ){ } or set(){key: value}
MutableYesNoYesYes
OrderedYesYesNoYes (3.7+)
IndexedYes (0-based)Yes (0-based)NoNo (access via keys)
Allows duplicatesYesYesNoKeys: No, Values: Yes
Element accessBy indexBy indexNot allowedBy key
Use caseGeneral-purpose collectionFixed data, read-only collectionsUnique items, set operationsStructured key-value mapping
Common methodsappend(), insert(), pop()count(), index()add(), remove(), union()get(), keys(), items()
Try Yourself

Quick Recap

Tap a question to reveal the answer.

How many else blocks can be used in an if structure?

Only one — and it must come last in the chain.

Which symbol represents the default case in match-case?

The underscore _.

What is the default start value of range()?

0 — range(stop) starts counting from 0 by default.

Which statement stops a loop immediately: continue, break, stop, or exit?

break.

What is the index of the first element in a list?

0 — Python indexing always starts at 0.

Which data structure does not allow duplicates?

Set. (Dictionary keys also can't duplicate, but values can.)

What does a & b represent for two sets?

Intersection — the elements common to both sets.

Which method safely retrieves a value from a dictionary without raising an error?

get() — it returns None (or a default) if the key doesn't exist, instead of raising a KeyError.

What is a tuple, and why is it called immutable?

A tuple is an ordered collection of items in parentheses. It is immutable because its contents cannot be changed, added to, or removed once created.

Differentiate between break and continue.

break exits the loop entirely. continue skips only the current iteration and moves on to the next one.